import React, { useState, useEffect } from 'react';
import { get } from 'lodash';

const loadedScripts = [];

//@ts-ignore
const jsAssets = window.jsAssets; // 依赖 locals，脚手架中提供的 jsAssets

const Loading = () => <div>加载中...</div>;

const ModuleComponent = ({ name }) => {
  const Component = get(window, `LiveApplication.Modules.${name}`);

  const [exists, setExists] = useState(!!Component);

  useEffect(() => {
    if (!exists) {
      const jsArrays = jsAssets[name];
      const loadScripts = jsArrays.filter((x) => !loadedScripts.includes(x));
      // 过滤掉已经加载的文件，但其实还是会加载，依赖项会被动态插入
      //@ts-ignore
      Promise.all(loadScripts.map((x) => window.CommonJsLoader.loadScript(x))).then(() => {
        setExists(true);
        loadedScripts.concat(loadScripts);
      });
    }
  }, []);

  return exists ? <Component /> : <Loading />;
};

class Application {
  //@ts-ignore
  static getComponent = (name) => () => <ModuleComponent name={name} />;

  static registeModule = (name, Component) => {
    //@ts-ignore
    if (!window.LiveApplication) {
      //@ts-ignore
      window.LiveApplication = {};
    }

    //@ts-ignore
    if (!window.LiveApplication.Modules) {
      //@ts-ignore
      window.LiveApplication.Modules = {};
    }

    //@ts-ignore
    window.LiveApplication.Modules[name] = Component;
  };

  //@ts-ignore
  static getFunctionModule = (name): any => window.LiveApplication.Modules[name];
}

export { Application };
